import React, { useState, useRef } from 'react';
import { connect } from 'umi';
import { formatMessage, FormattedMessage, getLocale } from 'umi';
import { message, Row, notification, Typography, ConfigProvider, Spin } from 'antd';
import { history } from 'umi';
import Login from '@/components/Login';
import withClearState from '@/utils/withClearState';
import zhCN from 'antd/es/locale/zh_CN';
import { genID } from '@/utils/utils';
import styles from './Login.less';

const { Paragraph } = Typography;
const { Tab, UserName, Password, Submit, ImgCaptcha } = Login;
const key = genID(18);
const LoginPage = ({ dispatch, submitting }) => {
    const [captchaNum, setCaptchaNum] = useState('');
    const loginForm = useRef(null);
    const [isVerificationCode, setIsVerificationCode] = useState(false);
    const [loading, setLoading] = useState(false);
    // 获取验证码
    const getCaptcha = () => {
        setLoading(true);
        dispatch({
            type: 'login/getImgCaptcha',
            payload: key,
            callback: res => {
                setCaptchaNum(res);
                setLoading(false);
            }
        });
    };
    const handleSubmit = (err, values) => {
        if (!err) {
            const regex = /zh[-_]cn/gi;
            const userLanguage = getLocale();
            const params = {
                username: values.username,
                password: values.password,
                client_id: '1422402458692440065', // 根据后端要求写死
                client_secret: '899730c05b2562b3f2e7fd2b400dfd06', // 根据后端要求写死
                verificationKey: key,
                verificationValue: values.ImgCaptcha
            };
            dispatch({
                type: 'login/login',
                payload: params,
                callback: res => {
                    if (res.code !== 10000) {
                        getCaptcha();
                    }
                    // 下一次登录需要验证码：code === 20100, 验证码错误 20010
                    if (res.code === 20100 || res.code === 20010) {
                        setIsVerificationCode(true);
                    }

                    if (res.code === 110110) {
                        notification.destroy();
                        notification.warning({
                            duration: null,
                            message: '登录邮箱错误',
                            description: (
                                <ConfigProvider locale={regex.test(userLanguage) ? zhCN : null}>
                                    您的企业账号已生成,请使用：
                                    <Paragraph copyable style={{ marginBottom: 0 }}>
                                        {res.msg}
                                    </Paragraph>
                                    登录VV WORK
                                </ConfigProvider>
                            )
                        });
                    } else {
                        message.error(res.msg);
                    }
                }
            });
        }
    };
    // useEffect(() => {
    //     // if (location.query && location.query.error === '40001') {
    //     //     message.error('该用户被禁用，请切换其他账号登陆！');
    //     // }
    // }, [count]);
    return (
        <div className={styles.main}>
            <Login defaultActiveKey="account" onSubmit={handleSubmit} ref={loginForm}>
                <Tab
                    key="account"
                    tab={formatMessage({
                        id: 'app.login.tab-login-credentials'
                    })}
                >
                    <UserName
                        name="username"
                        placeholder={`${formatMessage({
                            id: 'app.login.userName'
                        })}`}
                        rules={[
                            {
                                required: true,
                                message: formatMessage({
                                    id: 'validation.userName.required'
                                })
                            },
                            {
                                type: 'email',
                                message: formatMessage({
                                    id: 'validation.userName.wrong-format'
                                })
                            }
                        ]}
                        getValueFromEvent={e => e.target.value && e.target.value.trim()}
                    />
                    <Password
                        name="password"
                        placeholder={`${formatMessage({
                            id: 'app.login.password'
                        })}`}
                        rules={[
                            {
                                required: true,
                                message: formatMessage({
                                    id: 'validation.password.required'
                                })
                            },
                            {
                                validator(_, value, callback) {
                                    if (value && value.length < 8) {
                                        callback('密码长度不少于 8 个字符！');
                                    } else {
                                        callback();
                                    }
                                }
                            }
                        ]}
                        onPressEnter={e => {
                            e.preventDefault();
                            loginForm.current.validateFields(handleSubmit);
                        }}
                        getValueFromEvent={e => e.target.value && e.target.value.trim()}
                    />
                    {isVerificationCode && (
                        <Spin spinning={loading}>
                            <ImgCaptcha
                                name="ImgCaptcha"
                                value={captchaNum}
                                rules={[
                                    {
                                        required: true,
                                        message: formatMessage({
                                            id: 'validation.vercode.required'
                                        })
                                    }
                                ]}
                                placeholder={`${formatMessage({
                                    id: 'app.login.vercode'
                                })}`}
                                onClick={getCaptcha}
                            />
                        </Spin>
                    )}
                </Tab>
                <Row>
                    <a
                        style={{ float: 'right', paddingBottom: 10 }}
                        href="#"
                        onClick={e => {
                            e.preventDefault();
                            history.push('/user/forgot-password');
                        }}
                    >
                        <FormattedMessage id="app.login.forgot-password" />
                    </a>
                </Row>
                <Submit loading={submitting}>
                    <FormattedMessage id="app.login.login" />
                </Submit>
            </Login>
        </div>
    );
};

export default connect(({ login, loading }) => ({
    login,
    submitting: loading.effects['login/login']
}))(withClearState('login')(LoginPage));
